<?php

declare(strict_types=1);

namespace SixShop\Wangdian\Response;

/**
 * Represents an API response from Wangdian
 */
readonly class ApiResponse
{
    public function __construct(
        private array $data
    ) {
    }

    /**
     * Check if the response indicates success
     */
    public function isSuccess(): bool
    {
        return isset($this->data['code']) && (int) $this->data['code'] === 0;
    }

    /**
     * Get the response code
     */
    public function getCode(): int
    {
        return (int) ($this->data['code'] ?? -1);
    }

    /**
     * Get the response message
     */
    public function getMessage(): string
    {
        return $this->data['message'] ?? $this->data['msg'] ?? '';
    }

    /**
     * Get the response data
     */
    public function getData(): mixed
    {
        return $this->data['data'] ?? null;
    }

    /**
     * Get all response data
     */
    public function getRawData(): array
    {
        return $this->data;
    }

    /**
     * Convert response to array
     */
    public function toArray(): array
    {
        return $this->data;
    }

    /**
     * Convert response to JSON string
     */
    public function toJson(): string
    {
        return json_encode($this->data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    }

    /**
     * Check if a key exists in the response
     */
    public function has(string $key): bool
    {
        return isset($this->data[$key]);
    }

    /**
     * Get a value from the response by key
     */
    public function get(string $key, mixed $default = null): mixed
    {
        return $this->data[$key] ?? $default;
    }
}